{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# Claude Skills for Financial Applications\n\nBuild real-world financial dashboards, portfolio analytics, and automated reporting workflows using Claude's Excel, PowerPoint, and PDF skills.\n\n> **💡 Real-world Impact:** These are the same Skills that power **[Claude Creates Files](https://www.anthropic.com/news/create-files)**, enabling Claude to create professional financial documents directly in the interface.\n\n**What you'll learn:**\n- Create comprehensive financial models in Excel with formulas and charts\n- Generate executive presentations from financial data\n- Build portfolio analysis tools with risk metrics\n- Automate multi-format reporting pipelines"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Table of Contents\n",
    "\n",
    "1. [Setup & Data Loading](#setup)\n",
    "2. [Use Case 1: Financial Dashboard Creation](#financial-dashboard)\n",
    "   - [Excel Financial Model](#excel-model)\n",
    "   - [Executive PowerPoint](#executive-ppt)\n",
    "   - [PDF Financial Report](#pdf-report)\n",
    "3. [Use Case 2: Portfolio Analysis Workflow](#portfolio-analysis)\n",
    "   - [Portfolio Analytics Excel](#portfolio-excel)\n",
    "   - [Investment Committee Deck](#investment-deck)\n",
    "4. [Use Case 3: Automated Reporting Pipeline](#reporting-pipeline)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Prerequisites\n",
    "\n",
    "This notebook assumes you've completed **Notebook 1: Introduction to Skills**.\n",
    "\n",
    "If you haven't:\n",
    "1. Complete the setup in Notebook 1 first\n",
    "2. Verify your environment with the test cells\n",
    "3. Ensure you can create and download files\n",
    "\n",
    "**Required:**\n",
    "- Anthropic API key configured\n",
    "- SDK version 0.69.0 installed from whl\n",
    "- Virtual environment activated"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Setup & Data Loading {#setup}\n",
    "\n",
    "Let's start by importing our dependencies and loading the financial data we'll work with throughout this notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Standard imports\n",
    "import json\n",
    "import os\n",
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "import pandas as pd\n",
    "\n",
    "# Add parent directory for imports\n",
    "sys.path.insert(0, str(Path.cwd().parent))\n",
    "\n",
    "# Anthropic SDK\n",
    "from anthropic import Anthropic\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "# Our utilities\n",
    "from file_utils import (\n",
    "    download_all_files,\n",
    "    print_download_summary,\n",
    ")\n",
    "\n",
    "# Load environment\n",
    "load_dotenv(Path.cwd().parent / \".env\")\n",
    "\n",
    "# Configuration\n",
    "API_KEY = os.getenv(\"ANTHROPIC_API_KEY\")\n",
    "MODEL = \"claude-sonnet-4-5\"\n",
    "\n",
    "if not API_KEY:\n",
    "    raise ValueError(\"ANTHROPIC_API_KEY not found. Please configure your .env file.\")\n",
    "\n",
    "# Initialize client\n",
    "client = Anthropic(api_key=API_KEY)\n",
    "\n",
    "# Setup directories\n",
    "OUTPUT_DIR = Path.cwd().parent / \"outputs\" / \"financial\"\n",
    "OUTPUT_DIR.mkdir(parents=True, exist_ok=True)\n",
    "\n",
    "DATA_DIR = Path.cwd().parent / \"sample_data\"\n",
    "\n",
    "print(\"✓ Environment configured\")\n",
    "print(f\"✓ Output directory: {OUTPUT_DIR}\")\n",
    "print(f\"✓ Data directory: {DATA_DIR}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load Financial Data\n",
    "\n",
    "We have four datasets representing different aspects of a company's financial position:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load financial statements\n",
    "financial_statements = pd.read_csv(DATA_DIR / \"financial_statements.csv\")\n",
    "print(\"📊 Financial Statements Overview:\")\n",
    "print(f\"   Shape: {financial_statements.shape}\")\n",
    "print(f\"   Categories: {len(financial_statements['Category'].unique())} financial metrics\")\n",
    "print(f\"   Quarters: {list(financial_statements.columns[1:5])}\")\n",
    "print()\n",
    "\n",
    "# Show sample data\n",
    "print(\"Sample data (first 5 rows):\")\n",
    "financial_statements.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load portfolio holdings\n",
    "with open(DATA_DIR / \"portfolio_holdings.json\") as f:\n",
    "    portfolio_data = json.load(f)\n",
    "\n",
    "print(\"💼 Portfolio Overview:\")\n",
    "print(f\"   Portfolio: {portfolio_data['portfolio_name']}\")\n",
    "print(f\"   Total Value: ${portfolio_data['total_value']:,.2f}\")\n",
    "print(f\"   Holdings: {len(portfolio_data['holdings'])} stocks\")\n",
    "print(f\"   Cash Position: ${portfolio_data['cash_position']['amount']:,.2f}\")\n",
    "print(f\"   Total Return: {portfolio_data['performance_metrics']['total_return_percent']:.1f}%\")\n",
    "print()\n",
    "\n",
    "# Convert holdings to DataFrame for easier manipulation\n",
    "portfolio_df = pd.DataFrame(portfolio_data[\"holdings\"])\n",
    "print(\"Top 5 holdings by value:\")\n",
    "portfolio_df.nlargest(5, \"market_value\")[[\"ticker\", \"name\", \"market_value\", \"unrealized_gain\"]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load quarterly metrics\n",
    "with open(DATA_DIR / \"quarterly_metrics.json\") as f:\n",
    "    quarterly_metrics = json.load(f)\n",
    "\n",
    "print(\"📈 Quarterly Metrics Overview:\")\n",
    "print(f\"   Quarters available: {len(quarterly_metrics['quarters'])}\")\n",
    "print(f\"   Metrics per quarter: {len(quarterly_metrics['quarters'][0])} KPIs\")\n",
    "print()\n",
    "\n",
    "# Show latest quarter metrics\n",
    "latest_quarter = quarterly_metrics[\"quarters\"][-1]\n",
    "print(f\"Latest Quarter ({latest_quarter['quarter']}):\")\n",
    "for key, value in latest_quarter.items():\n",
    "    if key != \"quarter\" and isinstance(value, int | float):\n",
    "        if \"revenue\" in key.lower() or \"cost\" in key.lower():\n",
    "            print(f\"   {key.replace('_', ' ').title()}: ${value:,.0f}\")\n",
    "        elif \"percent\" in key.lower() or \"margin\" in key.lower() or \"rate\" in key.lower():\n",
    "            print(f\"   {key.replace('_', ' ').title()}: {value:.1f}%\")\n",
    "        else:\n",
    "            print(f\"   {key.replace('_', ' ').title()}: {value:,.0f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Helper Functions\n",
    "\n",
    "Let's define some helper functions for this notebook:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_skills_message(client, prompt, skills, prefix=\"\", show_token_usage=True):\n",
    "    \"\"\"\n",
    "    Helper function to create messages with Skills.\n",
    "\n",
    "    Args:\n",
    "        client: Anthropic client\n",
    "        prompt: User prompt\n",
    "        skills: List of skill dicts [{\"type\": \"anthropic\", \"skill_id\": \"xlsx\", \"version\": \"latest\"}]\n",
    "        prefix: Prefix for downloaded files\n",
    "        show_token_usage: Whether to print token usage\n",
    "\n",
    "    Returns:\n",
    "        Tuple of (response, download_results)\n",
    "    \"\"\"\n",
    "    response = client.beta.messages.create(\n",
    "        model=MODEL,\n",
    "        max_tokens=4096,\n",
    "        container={\"skills\": skills},\n",
    "        tools=[{\"type\": \"code_execution_20250825\", \"name\": \"code_execution\"}],\n",
    "        messages=[{\"role\": \"user\", \"content\": prompt}],\n",
    "        betas=[\n",
    "            \"code-execution-2025-08-25\",\n",
    "            \"files-api-2025-04-14\",\n",
    "            \"skills-2025-10-02\",\n",
    "        ],\n",
    "    )\n",
    "\n",
    "    if show_token_usage:\n",
    "        print(\n",
    "            f\"\\n📊 Token Usage: {response.usage.input_tokens} in, {response.usage.output_tokens} out\"\n",
    "        )\n",
    "\n",
    "    # Download files\n",
    "    results = download_all_files(client, response, output_dir=str(OUTPUT_DIR), prefix=prefix)\n",
    "\n",
    "    return response, results\n",
    "\n",
    "\n",
    "def format_financial_value(value, is_currency=True, decimals=0):\n",
    "    \"\"\"Format financial values for display.\"\"\"\n",
    "    if is_currency:\n",
    "        return f\"${value:,.{decimals}f}\"\n",
    "    else:\n",
    "        return f\"{value:,.{decimals}f}\"\n",
    "\n",
    "\n",
    "print(\"✓ Helper functions defined\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Use Case 1: Financial Dashboard Creation {#financial-dashboard}\n",
    "\n",
    "Now that we have our data loaded and helper functions defined, let's dive into our first practical use case: creating comprehensive financial dashboards. We'll start by generating multi-sheet Excel workbooks that automatically include formulas, formatting, and charts.\n",
    "\n",
    "### 2.1 Excel Financial Model {#excel-model}\n",
    "\n",
    "We'll create a financial dashboard that includes:\n",
    "- Profit & Loss statements with year-over-year comparisons\n",
    "- Balance sheet analysis\n",
    "- Cash flow tracking\n",
    "- KPI dashboards with visualizations\n",
    "\n",
    "This demonstrates how Claude's Skills can handle complex Excel generation tasks that would typically require hours of manual work."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create Financial Dashboard Excel\n",
    "print(\"Creating financial dashboard Excel file...\")\n",
    "print(\"This creates a 2-sheet dashboard optimized for the Skills API.\")\n",
    "print(\"\\n⏱️ Generation time: 1-2 minutes\\n\")\n",
    "\n",
    "# Prepare the financial data\n",
    "fs_data = financial_statements.to_dict(\"records\")\n",
    "quarters_2024 = [\"Q1_2024\", \"Q2_2024\", \"Q3_2024\", \"Q4_2024\"]\n",
    "\n",
    "# Extract key financial metrics\n",
    "revenue_by_quarter = {\n",
    "    \"Q1 2024\": financial_statements[financial_statements[\"Category\"] == \"Revenue\"][\n",
    "        \"Q1_2024\"\n",
    "    ].values[0],\n",
    "    \"Q2 2024\": financial_statements[financial_statements[\"Category\"] == \"Revenue\"][\n",
    "        \"Q2_2024\"\n",
    "    ].values[0],\n",
    "    \"Q3 2024\": financial_statements[financial_statements[\"Category\"] == \"Revenue\"][\n",
    "        \"Q3_2024\"\n",
    "    ].values[0],\n",
    "    \"Q4 2024\": financial_statements[financial_statements[\"Category\"] == \"Revenue\"][\n",
    "        \"Q4_2024\"\n",
    "    ].values[0],\n",
    "}\n",
    "\n",
    "financial_dashboard_prompt = f\"\"\"\n",
    "Create a financial dashboard Excel workbook with 2 sheets:\n",
    "\n",
    "Sheet 1 - \"P&L Summary\":\n",
    "Create a Profit & Loss summary table for 2024 quarters with these rows:\n",
    "- Revenue: {\", \".join([f\"Q{i + 1}: ${v / 1000000:.1f}M\" for i, v in enumerate(revenue_by_quarter.values())])}\n",
    "- Gross Profit: Use values from the data\n",
    "- Operating Income: Use values from the data\n",
    "- Net Income: Use values from the data\n",
    "- Add a Total column with SUM formulas\n",
    "- Add a row showing profit margins (Net Income / Revenue)\n",
    "- Apply currency formatting and bold headers\n",
    "- Add a simple bar chart showing quarterly revenue\n",
    "\n",
    "Sheet 2 - \"Key Metrics\":\n",
    "Create a metrics dashboard with:\n",
    "- Total Revenue 2024: SUM of all quarters\n",
    "- Average Quarterly Revenue: AVERAGE formula\n",
    "- Q4 vs Q1 Growth: Percentage increase\n",
    "- Best Quarter: MAX formula to identify\n",
    "- Operating Margin Q4: Calculate from data\n",
    "- Year-over-year growth vs 2023\n",
    "\n",
    "Apply professional formatting with borders, bold headers, and currency formats.\n",
    "\"\"\"\n",
    "\n",
    "# Create the Excel financial dashboard\n",
    "excel_response, excel_results = create_skills_message(\n",
    "    client,\n",
    "    financial_dashboard_prompt,\n",
    "    [{\"type\": \"anthropic\", \"skill_id\": \"xlsx\", \"version\": \"latest\"}],\n",
    "    prefix=\"financial_dashboard_\",\n",
    ")\n",
    "\n",
    "print(\"\\n\" + \"=\" * 60)\n",
    "print_download_summary(excel_results)\n",
    "\n",
    "if len(excel_results) > 0 and excel_results[0][\"success\"]:\n",
    "    print(\"\\n✅ Financial dashboard Excel created successfully!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 💡 Best Practices for Excel Generation\n",
    "\n",
    "Based on our testing, here are the optimal approaches for creating Excel files with Skills:\n",
    "\n",
    "**Recommended Approach:**\n",
    "- **2-3 sheets per workbook** works reliably and generates quickly\n",
    "- **Focus each sheet** on a specific purpose (e.g., P&L, metrics, charts)\n",
    "- **Add complexity incrementally** - start simple, then enhance\n",
    "\n",
    "**For Complex Dashboards:**\n",
    "1. **Create multiple focused files** instead of one complex file\n",
    "   - Example: `financial_pnl.xlsx`, `balance_sheet.xlsx`, `kpi_dashboard.xlsx`\n",
    "2. **Use the pipeline pattern** to create and enhance files sequentially\n",
    "3. **Combine files programmatically** using pandas or openpyxl if needed\n",
    "\n",
    "**Performance Tips:**\n",
    "- Simple 2-sheet dashboards: ~1-2 minutes\n",
    "- PowerPoint and PDF generation: Very reliable for complex content\n",
    "- Token usage: Structured data (JSON/CSV) is more efficient than prose"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.2 Executive PowerPoint {#executive-ppt}\n",
    "\n",
    "With our financial data now organized in Excel, let's create an executive presentation that summarizes the key insights. This demonstrates how Skills can generate professional PowerPoint presentations with charts, formatted text, and multiple slides - perfect for board meetings or investor updates.\n",
    "\n",
    "The presentation will include:\n",
    "- Q4 2024 performance highlights\n",
    "- Financial metrics with year-over-year comparisons\n",
    "- Profitability trends with visualizations\n",
    "- Key takeaways and outlook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Creating executive presentation from financial metrics...\")\n",
    "print(\"\\n⏱️ Generation time: 1-2 minutes\\n\")\n",
    "\n",
    "# Calculate some key metrics for the presentation\n",
    "q4_2024_revenue = 14500000\n",
    "q4_2023_revenue = 12300000\n",
    "yoy_growth = (q4_2024_revenue - q4_2023_revenue) / q4_2023_revenue * 100\n",
    "\n",
    "q4_2024_net_income = 1878750\n",
    "q4_2023_net_income = 1209000\n",
    "net_income_growth = (q4_2024_net_income - q4_2023_net_income) / q4_2023_net_income * 100\n",
    "\n",
    "executive_ppt_prompt = f\"\"\"\n",
    "Create a 4-slide executive presentation for Q4 2024 financial results:\n",
    "\n",
    "Slide 1 - Title:\n",
    "- Title: \"Q4 2024 Financial Results\"\n",
    "- Subtitle: \"Executive Summary - Acme Corporation\"\n",
    "- Date: January 2025\n",
    "\n",
    "Slide 2 - Financial Highlights:\n",
    "- Title: \"Q4 2024 Performance Highlights\"\n",
    "- Create a two-column layout:\n",
    "  Left side - Key Metrics:\n",
    "  • Revenue: $14.5M (+{yoy_growth:.1f}% YoY)\n",
    "  • Net Income: $1.88M (+{net_income_growth:.1f}% YoY)\n",
    "  • Operating Margin: 17.9% (up 2.9pp)\n",
    "  • Operating Cash Flow: $2.85M\n",
    "\n",
    "  Right side - Column chart showing quarterly revenue:\n",
    "  Q1 2024: $12.5M\n",
    "  Q2 2024: $13.2M\n",
    "  Q3 2024: $13.8M\n",
    "  Q4 2024: $14.5M\n",
    "\n",
    "Slide 3 - Profitability Trends:\n",
    "- Title: \"Margin Expansion & Profitability\"\n",
    "- Add a line chart showing net margin % by quarter:\n",
    "  Q1 2024: 11.4%\n",
    "  Q2 2024: 11.8%\n",
    "  Q3 2024: 12.4%\n",
    "  Q4 2024: 13.0%\n",
    "- Add bullet points below:\n",
    "  • Consistent margin expansion throughout 2024\n",
    "  • Operating leverage driving profitability\n",
    "  • Cost optimization initiatives delivering results\n",
    "\n",
    "Slide 4 - Key Takeaways:\n",
    "- Title: \"Key Takeaways & Outlook\"\n",
    "- Bullet points:\n",
    "  ✓ Record Q4 revenue of $14.5M\n",
    "  ✓ 17.9% YoY revenue growth\n",
    "  ✓ 55% increase in net income YoY\n",
    "  ✓ Strong cash generation: $2.85M operating cash flow\n",
    "  ✓ Well-positioned for continued growth in 2025\n",
    "\n",
    "Use professional corporate design:\n",
    "- Dark blue (#003366) for headers\n",
    "- Clean, modern layout\n",
    "- Data-driven visualizations\n",
    "\"\"\"\n",
    "\n",
    "# Create the executive presentation\n",
    "ppt_response, ppt_results = create_skills_message(\n",
    "    client,\n",
    "    executive_ppt_prompt,\n",
    "    [{\"type\": \"anthropic\", \"skill_id\": \"pptx\", \"version\": \"latest\"}],\n",
    "    prefix=\"executive_summary_\",\n",
    ")\n",
    "\n",
    "print(\"\\n\" + \"=\" * 60)\n",
    "print_download_summary(ppt_results)\n",
    "\n",
    "if len(ppt_results) > 0 and ppt_results[0][\"success\"]:\n",
    "    print(\"\\n✅ Executive presentation created successfully!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Use Case 2: Portfolio Analysis Workflow {#portfolio-analysis}\n",
    "\n",
    "Now let's shift our focus from company financials to investment portfolio analysis. In this section, we'll demonstrate how to create comprehensive portfolio analytics and investment committee presentations using the portfolio data we loaded earlier.\n",
    "\n",
    "This workflow showcases:\n",
    "- Detailed portfolio performance analysis in Excel\n",
    "- Risk metrics and sector allocation visualization\n",
    "- Professional investment committee presentations\n",
    "- Data-driven rebalancing recommendations\n",
    "\n",
    "We'll start by creating an Excel workbook with portfolio analytics, then generate an investment committee presentation that summarizes our findings."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### First, let's create a comprehensive portfolio analysis Excel workbook\n",
    "\n",
    "Before we create the investment committee presentation, we need to analyze our portfolio data in detail. This Excel workbook will serve as the foundation for our investment recommendations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Creating portfolio analysis Excel workbook...\")\n",
    "print(\"This creates a focused 2-sheet portfolio analysis optimized for the Skills API.\")\n",
    "print(\"\\n⏱️ Generation time: 1-2 minutes\\n\")\n",
    "\n",
    "# Prepare portfolio data for the prompt\n",
    "top_holdings = portfolio_df.nlargest(5, \"market_value\")\n",
    "sector_allocation = portfolio_data[\"sector_allocation\"]\n",
    "\n",
    "portfolio_excel_prompt = f\"\"\"\n",
    "Create a portfolio analysis Excel workbook with 2 sheets:\n",
    "\n",
    "Sheet 1 - \"Portfolio Overview\":\n",
    "Create a comprehensive holdings and performance table:\n",
    "\n",
    "Section 1 - Holdings (top of sheet):\n",
    "{portfolio_df[[\"ticker\", \"name\", \"shares\", \"current_price\", \"market_value\", \"unrealized_gain\", \"allocation_percent\"]].head(10).to_string()}\n",
    "\n",
    "Section 2 - Portfolio Summary:\n",
    "- Total portfolio value: ${portfolio_data[\"total_value\"]:,.2f}\n",
    "- Total unrealized gain: ${portfolio_df[\"unrealized_gain\"].sum():,.2f}\n",
    "- Total Return: {portfolio_data[\"performance_metrics\"][\"total_return_percent\"]:.1f}%\n",
    "- YTD Return: {portfolio_data[\"performance_metrics\"][\"year_to_date_return\"]:.1f}%\n",
    "- Sharpe Ratio: {portfolio_data[\"performance_metrics\"][\"sharpe_ratio\"]:.2f}\n",
    "- Portfolio Beta: {portfolio_data[\"performance_metrics\"][\"beta\"]:.2f}\n",
    "\n",
    "Apply conditional formatting: green for gains, red for losses.\n",
    "Add a bar chart showing top 5 holdings by value.\n",
    "\n",
    "Sheet 2 - \"Sector Analysis & Risk\":\n",
    "Create sector allocation and risk metrics:\n",
    "\n",
    "Section 1 - Sector Allocation:\n",
    "{json.dumps(sector_allocation, indent=2)}\n",
    "Include a pie chart of sector allocation.\n",
    "\n",
    "Section 2 - Key Risk Metrics:\n",
    "- Portfolio Beta: {portfolio_data[\"performance_metrics\"][\"beta\"]:.2f}\n",
    "- Standard Deviation: {portfolio_data[\"performance_metrics\"][\"standard_deviation\"]:.1f}%\n",
    "- Value at Risk (95%): $62,500\n",
    "- Maximum Drawdown: -12.3%\n",
    "- Sharpe Ratio: {portfolio_data[\"performance_metrics\"][\"sharpe_ratio\"]:.2f}\n",
    "\n",
    "Section 3 - Rebalancing Recommendations:\n",
    "- Reduce Technology from 20% to 18%\n",
    "- Increase Healthcare from 8.7% to 10%\n",
    "- Maintain current diversification\n",
    "\n",
    "Apply professional formatting with clear sections and headers.\n",
    "\"\"\"\n",
    "\n",
    "# Create portfolio analysis Excel\n",
    "portfolio_response, portfolio_results = create_skills_message(\n",
    "    client,\n",
    "    portfolio_excel_prompt,\n",
    "    [{\"type\": \"anthropic\", \"skill_id\": \"xlsx\", \"version\": \"latest\"}],\n",
    "    prefix=\"portfolio_analysis_\",\n",
    ")\n",
    "\n",
    "print(\"\\n\" + \"=\" * 60)\n",
    "print_download_summary(portfolio_results)\n",
    "\n",
    "if len(portfolio_results) > 0 and portfolio_results[0][\"success\"]:\n",
    "    print(\"\\n✅ Portfolio analysis Excel created successfully!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.2 Investment Committee Presentation {#investment-deck}\n",
    "\n",
    "With our detailed portfolio analysis complete, let's now create a professional presentation for the investment committee. This presentation will distill the key insights from our Excel analysis into a concise, visual format suitable for decision-makers.\n",
    "\n",
    "The presentation will cover:\n",
    "- Portfolio performance summary with key metrics\n",
    "- Asset allocation and diversification analysis\n",
    "- Risk metrics and risk-adjusted returns\n",
    "- Strategic recommendations for rebalancing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Creating investment committee presentation...\")\n",
    "print(\"\\n⏱️ Generation time: 1-2 minutes\\n\")\n",
    "\n",
    "investment_deck_prompt = f\"\"\"\n",
    "Create a 5-slide investment committee presentation:\n",
    "\n",
    "Slide 1 - Title:\n",
    "- Title: \"Portfolio Review - Q4 2024\"\n",
    "- Subtitle: \"{portfolio_data[\"portfolio_name\"]}\"\n",
    "- Date: January 2025\n",
    "- Portfolio Value: ${portfolio_data[\"total_value\"]:,.0f}\n",
    "\n",
    "Slide 2 - Portfolio Overview:\n",
    "- Title: \"Portfolio Performance Summary\"\n",
    "- Two-column layout:\n",
    "\n",
    "  Left - Key Metrics:\n",
    "  • Total Value: ${portfolio_data[\"total_value\"]:,.0f}\n",
    "  • YTD Return: +{portfolio_data[\"performance_metrics\"][\"year_to_date_return\"]:.1f}%\n",
    "  • Total Return: ${portfolio_data[\"performance_metrics\"][\"total_return\"]:,.0f}\n",
    "  • Sharpe Ratio: {portfolio_data[\"performance_metrics\"][\"sharpe_ratio\"]:.2f}\n",
    "\n",
    "  Right - Bar chart of top 5 holdings by value:\n",
    "  {\", \".join([f\"{h['ticker']}: ${h['market_value']:,.0f}\" for h in top_holdings.to_dict(\"records\")])}\n",
    "\n",
    "Slide 3 - Sector Allocation:\n",
    "- Title: \"Asset Allocation & Diversification\"\n",
    "- Pie chart showing:\n",
    "  Technology: {sector_allocation[\"Technology\"]:.1f}%\n",
    "  Financials: {sector_allocation[\"Financials\"]:.1f}%\n",
    "  Healthcare: {sector_allocation[\"Healthcare\"]:.1f}%\n",
    "  Consumer: {sector_allocation[\"Consumer Discretionary\"] + sector_allocation[\"Consumer Staples\"]:.1f}%\n",
    "  Fixed Income: {sector_allocation[\"Bonds\"]:.1f}%\n",
    "  Cash: {sector_allocation[\"Cash\"]:.1f}%\n",
    "\n",
    "Slide 4 - Risk Analysis:\n",
    "- Title: \"Risk Metrics & Analysis\"\n",
    "- Content:\n",
    "  Risk Indicators:\n",
    "  • Portfolio Beta: {portfolio_data[\"performance_metrics\"][\"beta\"]:.2f} (lower market risk)\n",
    "  • Standard Deviation: {portfolio_data[\"performance_metrics\"][\"standard_deviation\"]:.1f}%\n",
    "  • Maximum Drawdown: -12.3%\n",
    "  • Value at Risk (95%): $62,500\n",
    "\n",
    "  Risk-Adjusted Performance:\n",
    "  • Sharpe Ratio: {portfolio_data[\"performance_metrics\"][\"sharpe_ratio\"]:.2f} (excellent)\n",
    "  • Alpha Generation: +2.3% vs benchmark\n",
    "\n",
    "Slide 5 - Recommendations:\n",
    "- Title: \"Strategic Recommendations\"\n",
    "- Bullet points:\n",
    "  ✓ Maintain current allocation - well diversified\n",
    "  ✓ Consider profit-taking in Technology (20% → 18%)\n",
    "  ✓ Increase Healthcare allocation (8.7% → 10%)\n",
    "  ✓ Monitor bond duration given rate environment\n",
    "  ✓ Rebalance quarterly to maintain targets\n",
    "\n",
    "Use professional investment presentation design.\n",
    "\"\"\"\n",
    "\n",
    "# Create investment committee deck\n",
    "investment_response, investment_results = create_skills_message(\n",
    "    client,\n",
    "    investment_deck_prompt,\n",
    "    [{\"type\": \"anthropic\", \"skill_id\": \"pptx\", \"version\": \"latest\"}],\n",
    "    prefix=\"investment_committee_\",\n",
    ")\n",
    "\n",
    "print(\"\\n\" + \"=\" * 60)\n",
    "print_download_summary(investment_results)\n",
    "print(\"\\n✅ Investment committee presentation created successfully!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Use Case 3: Automated Reporting Pipeline {#reporting-pipeline}\n",
    "\n",
    "So far, we've created individual documents for specific purposes. Now let's demonstrate the power of chaining multiple Skills together in an automated workflow. This pipeline pattern is essential for production systems where you need to generate multiple related documents from the same data source.\n",
    "\n",
    "In this example, we'll create a complete reporting suite that:\n",
    "1. **Analyzes data** in Excel with calculations and charts\n",
    "2. **Summarizes insights** in a PowerPoint presentation\n",
    "3. **Documents the process** in a formal PDF report\n",
    "\n",
    "This showcases how Skills can work together to create a comprehensive reporting solution that would traditionally require multiple tools and manual coordination.\n",
    "\n",
    "**Key benefits of the pipeline approach:**\n",
    "- Consistent data across all documents\n",
    "- Reduced total generation time\n",
    "- Token usage optimization\n",
    "- Scalable to multiple report types\n",
    "\n",
    "**⏱️ Total expected time:** 2-3 minutes for the complete pipeline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"🔄 Starting Automated Reporting Pipeline\")\n",
    "print(\"=\" * 60)\n",
    "print(\"This will create a complete reporting suite:\")\n",
    "print(\"1. Excel analysis → 2. PowerPoint summary → 3. PDF documentation\")\n",
    "print(\"\\n⏱️ Total pipeline time: 2-3 minutes\\n\")\n",
    "\n",
    "# Track token usage across the pipeline\n",
    "pipeline_tokens = {\"input\": 0, \"output\": 0}\n",
    "\n",
    "# Step 1: Create Excel Analysis\n",
    "print(\"Step 1/3: Creating Excel analysis with quarterly metrics...\")\n",
    "\n",
    "excel_pipeline_prompt = f\"\"\"\n",
    "Create a quarterly business metrics Excel file:\n",
    "\n",
    "Sheet 1 - \"Quarterly KPIs\":\n",
    "Create a table with these quarterly metrics for 2024:\n",
    "{\n",
    "    json.dumps(\n",
    "        [\n",
    "            {\n",
    "                k: v\n",
    "                for k, v in q.items()\n",
    "                if k in [\"quarter\", \"revenue\", \"gross_margin\", \"customer_count\", \"churn_rate\"]\n",
    "            }\n",
    "            for q in quarterly_metrics[\"quarters\"]\n",
    "        ],\n",
    "        indent=2,\n",
    "    )\n",
    "}\n",
    "\n",
    "Add:\n",
    "- Quarter-over-quarter growth calculations\n",
    "- Average and total rows\n",
    "- Conditional formatting for trends\n",
    "- Line chart showing revenue trend\n",
    "- Column chart showing customer count\n",
    "\n",
    "Sheet 2 - \"YoY Comparison\":\n",
    "Compare Q4 2024 vs Q4 2023 for all metrics.\n",
    "Calculate percentage changes and highlight improvements.\n",
    "\n",
    "Professional formatting with headers and borders.\n",
    "\"\"\"\n",
    "\n",
    "excel_response, excel_results = create_skills_message(\n",
    "    client,\n",
    "    excel_pipeline_prompt,\n",
    "    [{\"type\": \"anthropic\", \"skill_id\": \"xlsx\", \"version\": \"latest\"}],\n",
    "    prefix=\"pipeline_1_metrics_\",\n",
    "    show_token_usage=False,\n",
    ")\n",
    "\n",
    "pipeline_tokens[\"input\"] += excel_response.usage.input_tokens\n",
    "pipeline_tokens[\"output\"] += excel_response.usage.output_tokens\n",
    "print(\n",
    "    f\"✓ Excel created - Tokens: {excel_response.usage.input_tokens} in, {excel_response.usage.output_tokens} out\"\n",
    ")\n",
    "\n",
    "# Step 2: Create PowerPoint Summary\n",
    "print(\"\\nStep 2/3: Creating PowerPoint summary from metrics...\")\n",
    "\n",
    "ppt_pipeline_prompt = \"\"\"\n",
    "Create a 3-slide quarterly metrics summary presentation:\n",
    "\n",
    "Slide 1:\n",
    "- Title: \"Q4 2024 Metrics Summary\"\n",
    "- Subtitle: \"Automated Reporting Pipeline Demo\"\n",
    "\n",
    "Slide 2:\n",
    "- Title: \"Key Performance Indicators\"\n",
    "- Show Q4 2024 metrics:\n",
    "  • Revenue: $3.2M (+15% QoQ)\n",
    "  • Customers: 850 (+8.9% QoQ)\n",
    "  • Gross Margin: 72%\n",
    "  • Churn Rate: 2.8% (improved from 3.5%)\n",
    "- Add a simple bar chart comparing Q3 vs Q4 revenue\n",
    "\n",
    "Slide 3:\n",
    "- Title: \"Quarterly Trend Analysis\"\n",
    "- Line chart showing revenue growth Q1-Q4\n",
    "- Key insight bullets:\n",
    "  • Consistent QoQ growth\n",
    "  • Customer acquisition accelerating\n",
    "  • Churn reduction successful\n",
    "\n",
    "Clean, data-focused design.\n",
    "\"\"\"\n",
    "\n",
    "ppt_response, ppt_results = create_skills_message(\n",
    "    client,\n",
    "    ppt_pipeline_prompt,\n",
    "    [{\"type\": \"anthropic\", \"skill_id\": \"pptx\", \"version\": \"latest\"}],\n",
    "    prefix=\"pipeline_2_summary_\",\n",
    "    show_token_usage=False,\n",
    ")\n",
    "\n",
    "pipeline_tokens[\"input\"] += ppt_response.usage.input_tokens\n",
    "pipeline_tokens[\"output\"] += ppt_response.usage.output_tokens\n",
    "print(\n",
    "    f\"✓ PowerPoint created - Tokens: {ppt_response.usage.input_tokens} in, {ppt_response.usage.output_tokens} out\"\n",
    ")\n",
    "\n",
    "# Step 3: Create PDF Documentation\n",
    "print(\"\\nStep 3/3: Creating PDF documentation...\")\n",
    "\n",
    "pdf_pipeline_prompt = \"\"\"\n",
    "Create a PDF document summarizing the quarterly reporting pipeline:\n",
    "\n",
    "AUTOMATED REPORTING PIPELINE\n",
    "Q4 2024 Results Documentation\n",
    "\n",
    "EXECUTIVE SUMMARY\n",
    "This document summarizes the Q4 2024 business metrics generated through\n",
    "our automated reporting pipeline.\n",
    "\n",
    "KEY METRICS\n",
    "- Revenue: $3.2M (15% QoQ growth)\n",
    "- Customer Base: 850 active customers\n",
    "- Gross Margin: 72%\n",
    "- Churn Rate: 2.8% (improved from 3.5%)\n",
    "\n",
    "PIPELINE COMPONENTS\n",
    "1. Data Processing: Quarterly metrics analyzed in Excel\n",
    "2. Visualization: Key insights presented in PowerPoint\n",
    "3. Documentation: Formal report generated in PDF\n",
    "\n",
    "AUTOMATION BENEFITS\n",
    "• Reduced reporting time by 90%\n",
    "• Consistent format and quality\n",
    "• Eliminated manual errors\n",
    "• Scalable to multiple reports\n",
    "\n",
    "NEXT STEPS\n",
    "- Expand pipeline to include predictive analytics\n",
    "- Add automated email distribution\n",
    "- Implement real-time data feeds\n",
    "\n",
    "Generated: January 2025\n",
    "Pipeline Version: 1.0\n",
    "\n",
    "Format as a professional technical document.\n",
    "\"\"\"\n",
    "\n",
    "pdf_response, pdf_results = create_skills_message(\n",
    "    client,\n",
    "    pdf_pipeline_prompt,\n",
    "    [{\"type\": \"anthropic\", \"skill_id\": \"pdf\", \"version\": \"latest\"}],\n",
    "    prefix=\"pipeline_3_documentation_\",\n",
    "    show_token_usage=False,\n",
    ")\n",
    "\n",
    "pipeline_tokens[\"input\"] += pdf_response.usage.input_tokens\n",
    "pipeline_tokens[\"output\"] += pdf_response.usage.output_tokens\n",
    "print(\n",
    "    f\"✓ PDF created - Tokens: {pdf_response.usage.input_tokens} in, {pdf_response.usage.output_tokens} out\"\n",
    ")\n",
    "\n",
    "# Pipeline Summary\n",
    "print(\"\\n\" + \"=\" * 60)\n",
    "print(\"🎯 PIPELINE COMPLETE!\")\n",
    "print(\"=\" * 60)\n",
    "\n",
    "print(\"\\n📊 Pipeline Token Usage Summary:\")\n",
    "print(f\"   Total Input Tokens: {pipeline_tokens['input']:,}\")\n",
    "print(f\"   Total Output Tokens: {pipeline_tokens['output']:,}\")\n",
    "print(f\"   Total Tokens: {pipeline_tokens['input'] + pipeline_tokens['output']:,}\")\n",
    "print(f\"   Average per document: {(pipeline_tokens['input'] + pipeline_tokens['output']) // 3:,}\")\n",
    "\n",
    "print(\"\\n📁 Generated Files:\")\n",
    "all_results = excel_results + ppt_results + pdf_results\n",
    "for i, result in enumerate(all_results, 1):\n",
    "    if result[\"success\"]:\n",
    "        print(f\"   {i}. {os.path.basename(result['output_path'])} ({result['size'] / 1024:.1f} KB)\")\n",
    "\n",
    "print(\"\\n✅ Automated reporting pipeline executed successfully!\")\n",
    "print(\"   All three documents created and linked in workflow.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Summary & Next Steps\n\n### What We've Accomplished\n\nIn this notebook, you've learned how to:\n\n✅ **Financial Dashboard Creation**\n- Built multi-sheet Excel models with formulas and charts\n- Generated executive PowerPoint presentations\n- Created professional PDF reports\n\n✅ **Portfolio Analysis**\n- Developed portfolio analytics workbooks\n- Created investment committee presentations\n- Implemented risk metrics and rebalancing tools\n\n✅ **Automated Pipelines**\n- Chained multiple document formats\n- Optimized token usage\n- Built production-ready patterns\n\n### Key Takeaways\n\n1. **Skills dramatically simplify financial document creation** - What would take hours manually takes minutes\n2. **Token efficiency is excellent** - Skills use ~90% fewer tokens than manual instructions\n3. **Quality is professional-grade** - Documents are immediately usable in business contexts\n4. **Automation is straightforward** - Pipeline patterns enable complex workflows\n\n### Continue Your Learning\n\n📚 **Next: [Notebook 3 - Custom Skills Development](03_skills_custom_development.ipynb)**\n- Build your own specialized financial skills\n- Create company-specific templates\n- Implement advanced automation\n\n### Try These Experiments\n\n1. **Modify the financial dashboard** to include your own metrics\n2. **Create a custom portfolio** with different asset classes\n3. **Build a pipeline** for your specific reporting needs\n4. **Experiment with complexity** to understand generation times\n5. **Track token usage** across different document types\n\n### Resources\n\n- [Claude API Documentation](https://docs.anthropic.com/en/api/messages)\n- [Skills Documentation](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/overview)\n- [Best Practices](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/best-practices)\n- [Files API Reference](https://docs.claude.com/en/api/files-content)"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}